﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ServisniList.Core;

namespace ServisniList
{
    public partial class UlaznaForma : Form
    {
        #region Properties

        public bool LoginStatus { get; set; }

        #endregion

        #region  Fields

        private bool izlazIzAplikacije = true;

        #endregion

        #region Constructor

        public UlaznaForma()
        {
            InitializeComponent();
            izlazIzAplikacije = true;
        }

        #endregion

        #region Event handlers

        private void UlaznaForma_Load(object sender, EventArgs e)
        {
#if DEBUG

            txtKorisnik.Text = "admin";
            txtLozinka.Text = "passw0rd";
            btnUlaz_Click(this, new EventArgs());
#endif
        }

        private void btnUlaz_Click(object sender, EventArgs e)
        {
            LoginStatus = checkCredentials(txtKorisnik.Text, txtLozinka.Text);
            if (LoginStatus)
            {
                izlazIzAplikacije = false;
                ServisniListUnos sListUnos = new ServisniListUnos();
                sListUnos.Show();
                this.Close();
            }
            else
            {
                lblError.Text = "Neuspješan ulaz !";
            }
        }

        private void UlaznaForma_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (izlazIzAplikacije)
            {
                Application.Exit();
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.KeyCode == Keys.Escape)
                this.Close();
        }

        #endregion

        #region Methods

        private bool checkCredentials(string korisnik, string password)
        {
            using (DataModelDataContext context = new DataModelDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ServisniListConnectionString"].ConnectionString))
            {
                var korisnici = context.Djelatniks.ToList();

                Rukovatelji.Korisnici.GetInstance().TreutnoUlogiraniDjelatnik = (from kor in korisnici
                                                                                  where kor.Naziv == korisnik
                                                                                  && kor.Lozinka == password
                                                                                  select kor).FirstOrDefault();
            }

            if (Rukovatelji.Korisnici.GetInstance().TreutnoUlogiraniDjelatnik != null)
                return true;
            return false;
        }

        #endregion

    }
}
